
import { _decorator, Component, Node, resources, Prefab, instantiate, EventTarget, director } from 'cc';
const { ccclass, property } = _decorator;

export default class App extends EventTarget {

    private static _ins: App;

    public static get Ins(): App {
        if (!App._ins)
            App._ins = new App;
        return App._ins;
    }

    public ui: Node = null;

    constructor() {
        super();

        this.on('ui-ready', this.onUIReady, this);
    }

    onUIReady() {
        this.openUI();
    }

    loadPrefab() {
        resources.load('UI', Prefab, (err, prefab) => {
            if (err)
                return console.error(err);

            console.log('prefab加载成功');
            App.Ins.ui = instantiate(prefab);
            this.emit('ui-ready');
        })
    }

    openUI() {
        if (!this.ui)
            return this.loadPrefab();

        if (!this.ui.isValid) 
            return;

        let root = director.getScene().getChildByName('Canvas');
        this.ui.active = true;
        root.addChild(this.ui);
    }

    closeUI() {
        this.ui.active = false;
        this.ui.parent = null;
    }
}
